# -*- coding: utf-8 -*-

from django import template
from django.utils.safestring import mark_safe
from django.template.defaultfilters import stringfilter
import calendar
from django.core.urlresolvers import reverse

register = template.Library()

@register.filter
@stringfilter
def color_balance(x):
    try: x = float(x)
    except: return x
    if x >= 0:
        cls = u'positive-balance'
    else:
        cls = u'negative-balance'
    return mark_safe(u'<span class="%s">%.2f грн.</span>' % (cls, x))

@register.filter
@stringfilter
def insert_id(s, request):
    try: id = request.statuser.id
    except:
        try: id = request.user.id
        except: return s
    return s.replace(u'%d', str(id))

@register.filter
def human_bytes(s):
    try: n = float(s)
    except: return u"error"
    if n is None: n = 0
    if n < 1024: return str(int(n)) + u' Б'
    n = n / 1024
    if n < 1024: return ('%0.2f' % (n, )) + u' кБ'
    n = n / 1024
    if n < 1024: return ('%0.2f' % (n, )) + u' МБ'
    n = n / 1024
    return (u'%0.2f' % n) + u' ГБ'

@register.filter
def human_cost(s):
    try: n = float(s)*100
    except: return 'error'
    return u"%.2f коп. за МБ" % n

@register.filter
def time2str(dt, min=300):
    import time, datetime
    #return str(dt.timetuple())+'\n'+str(time.localtime())
    delta = datetime.datetime.now() - dt
    t = 86400 * delta.days + delta.seconds
    def get_seconds(c):
        if c % 100 in xrange(10,20): return u'секунд'
        elif c % 10 == 1: return u'секунду'
        elif c % 10 in [2, 3, 4]: return u'секунды'
        else: return u'секунд'

    def get_minutes(c):
        if c % 100 in xrange(10,20): return u'минут'
        elif c % 10 == 1: return u'минуту'
        elif c % 10 in [2, 3, 4]: return u'минуты'
        else: return u'минут'

    def get_hours(c):
        if c % 100 in xrange(10,20): return u'часов'
        elif c % 10 == 1: return u'час'
        elif c % 10 in [2, 3, 4]: return u'часа'
        else: return u'часов'

    def get_days(c):
        if c % 100 in xrange(10,20): return u'дней'
        elif c % 10 == 1: return u'день'
        elif c % 10 in [2, 3, 4]: return u'дня'
        else: return u'дней'

    def get_months(c):
        if c % 100 in xrange(10,20): return u'месяцев'
        elif c % 10 == 1: return u'месяц'
        elif c % 10 in [2, 3, 4]: return u'месяца'
        else: return u'месяцев'

    minutes, seconds = divmod(t, 60)
    hours, minutes = divmod(minutes, 60)
    days, hours = divmod(hours, 24)
    months, days = divmod(days, 30)
    if t<min: return u'сейчас'
    r = u'%d %s назад' % (t, get_seconds(round(seconds)))
    if t>60: r = u'%d %s' % (minutes, get_minutes(round(minutes)))
    else: return r
    if t>3600: r = u'%d %s %s' % (hours, get_hours(round(hours)), r)
    if t>86400: r = u'%d %s %s' % (days, get_days(round(days)), r)
    if t>2592000: r = u'%d %s %s' % (months, get_months(round(months)), r)
    if t>86400*365*10: return u'никогда' # больше десяти лет назад
    return r + u' назад'

@register.simple_tag
def depth_title(depth):
    return [u"Год", u"Месяц", u"День", u"Часы"][depth]

@register.filter
def depth_unit(count, depth):
    months = [u'', u'январь', u'февраль', u'март', u'апрель', u'май', \
        u'июнь', u'июль', u'август', u'сентябрь', u'октябрь', \
        u'ноябрь', u'декабрь']
    count = int(count)
    if depth in [0, 2]: return str(count)
    elif depth == 1: return months[count]
    elif depth == 3: return u"%d:00 - %d:00" % (count, count+1)
    else: return str(count)

@register.simple_tag
def stats_url(profile, category, year=None, month=None, day=None, depth=None, ext=None):
    if ext:
        if depth == 0: year = int(ext)
        elif depth == 1: month = int(ext)
        elif depth == 2: day = int(ext)
        else: hour = int(ext)
    if profile: url = reverse("stats", kwargs={"statuser": profile.user.id})
    else: url = reverse("stats")
    q = u"&".join([ \
        u"%s=%s" % (unit, eval(unit)) \
        for unit in ["category", "year", "month", "day"] \
        if eval(unit)])
    if q: url = "%s?%s" % (url, q)
    return url

@register.simple_tag
def traffic_path(profile, category, year, month, day):
    depth = 0
    while depth<3 and [year, month, day][depth]:
        depth += 1
    sep = "<span class='sep'>/</span>"
    units = []
    units.append("<a href='%s'>%s</a>" % (stats_url(profile, category), u"Всё"))
    if depth > 0:
        units.append("<a href='%s'>%s</a>" % (stats_url(profile, category, year), \
        depth_unit(year, 0)))
    if depth > 1:
        units.append("<a href='%s'>%s</a>" % (stats_url(profile, category, year, \
        month), depth_unit(month, 1)))
    if depth > 2:
        units.append("<a href='%s'>%s</a>" % (stats_url(profile, category, year, \
        month, day), depth_unit(day, 2)))
    return sep.join(units)

@register.simple_tag
def obsolete_warning(request):
    ip = request.META['REMOTE_ADDR']
    if not ip.startswith("192.168.8."): # hardcode
        return u"""
        <div class='obsolete_warning'>
        Ваш IP адрес %s, для нормальной работы нужно изменить сетевые
        настройки в соответствии с <a href="%s#settings">инструкцией</a>
        </div>
        """ % (ip, reverse("help"))
    else: return u""
